package org.example.task;

import java.io.InputStream;

/**
 * @author L.xf
 * @date 2021/9/15
 */
public class XlassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        ClassLoader classLoader = this.getClass().getClassLoader();
        System.out.println(classLoader.getResource("META-INF"));
        try (InputStream inputStream = classLoader.getResourceAsStream("META-INF/" + name + ".xlass")) {
            int available = inputStream.available();
            byte[] bytes = new byte[available];
            inputStream.read(bytes);
            byte[] classBytes = decode(bytes);
            return super.defineClass(name, classBytes, 0, classBytes.length);
        } catch (Exception e) {
            throw new ClassNotFoundException(e.getMessage());
        }
    }

    private static byte[] decode(byte[] bytes) {
        byte[] target = new byte[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            target[i] = (byte) (255 - bytes[i]);
        }
        return target;
    }

    public static void main(String[] args) throws Exception {
        // 获取classload
        ClassLoader clazzLoad = new XlassLoader();

//         加载类
        Class<?> clazz = clazzLoad.loadClass("Hello");

//         通过反射 默认构造函数生成 对象
        Object obj = clazz.getDeclaredConstructor().newInstance();
//         反射执行 方法
        clazz.getMethod("hello").invoke(obj);

    }
}
